package com.zed.api.common.localstore;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.file.Path;

/**
 * 本地存储工具类
 *
 * @author Zed
 */
public abstract class LocalStoreUtils {

    private static LocalStore INSTANCE = new LocalStore() {

        private Path workspace;

        /**
         * 判断是否windows系统
         *
         * @return 如果是返回true, 否则是false
         */
        private boolean isWindows() {
            String os = System.getProperty("os.name").toLowerCase();
            return os.startsWith("win");
        }


        @Override
        public Path getWorkingDirectory() {
            if (this.workspace == null) {
                URL url = this.getClass().getClassLoader().getResource("/");
                if (url == null) {
                    url = this.getClass().getClassLoader().getResource("");
                }

                if (url.getProtocol().equals("file")) {
                    try {
                        String path = URLDecoder.decode(url.getPath(), "utf-8");
                        File file = new File(path);
                        File parent = file.getParentFile();
                        this.workspace = new File(parent, "workspace").toPath();
                    } catch (UnsupportedEncodingException e) {

                    }
                }

                if (url.getProtocol().equals("jar")) {
                    try {
                        JarURLConnection conn = (JarURLConnection) url.openConnection();
                        String jarFile = conn.getJarFileURL().getFile();
                        int startIndex = isWindows() ? 6 : 5;
                        jarFile = jarFile.substring(startIndex, jarFile.indexOf("!"));
                        File file = new File(jarFile);
                        File parent = file.getParentFile();
                        this.workspace = new File(parent, "workspace").toPath();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                if (this.workspace == null) {
                    throw new RuntimeException("cannot locate workspace directory.");
                } else {
                    this.workspace.toFile().mkdirs();
                }
            }
            return this.workspace;
        }
    };

    /**
     * 获取单列
     *
     * @return {@link LocalStore}
     */
    public static LocalStore getInstance() {
        return INSTANCE;
    }

}
